<template>
  <el-dialog
    :title="formData.topicId ? '编辑话题' : '新增话题'"
    v-model="visible"
    width="500px"
    @close="close"
  >
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入话题标题" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" placeholder="请输入描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="submit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineExpose } from 'vue'
import { ElMessage } from 'element-plus'

const visible = ref(false)
const formRef = ref(null)
const formData = reactive({
  topicId: null,
  title: '',
  description: ''
})
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
}

const emit = defineEmits(['refresh-data-list'])

function init(id) {
  if (id) {
    // 编辑，加载详情
    http({
      url: http.adornUrl(`/social/topic/detail/${id}`),
      method: 'get'
    }).then(({ data }) => {
      Object.assign(formData, data)
      visible.value = true
    })
  } else {
    // 新增
    formData.topicId = null
    formData.title = ''
    formData.description = ''
    visible.value = true
  }
}

function close() {
  visible.value = false
}

function submit() {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    const isEdit = !!formData.topicId
    await http({
      url: http.adornUrl('/social/topic' + (isEdit ? '' : '')),
      method: isEdit ? 'post' : 'post',
      data: formData
    })
    ElMessage.success(isEdit ? '编辑成功' : '新增成功')
    visible.value = false
    emit('refresh-data-list')
  })
}

const formatTime = (time) => {
  if (!time) return '-'
  const d = new Date(time)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

defineExpose({ init })
</script>

<style scoped>
.topic-posts-title {
  font-size: 15px;
  font-weight: bold;
  margin: 12px 0 4px 0;
  color: #333;
}
.topic-posts-list {
  margin-bottom: 8px;
}
.topic-post-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  background: #f8fafd;
  border-radius: 4px;
  padding: 6px 8px;
}
.post-content {
  flex: 1;
  color: #444;
  font-size: 14px;
}
.post-media {
  margin-left: 8px;
}
.post-time {
  font-size: 12px;
  color: #aaa;
  margin-left: 12px;
  min-width: 110px;
  text-align: right;
}
.no-posts {
  color: #bbb;
  text-align: center;
  padding: 8px 0;
}
</style>
